package com.wsl.irremoter;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
 
public class IRemoterMainActivity extends Activity {
	private final static String LIRCD_CONF_FILE = "/sdcard/tmp/t.conf";

	Lirc lirc;
	ArrayAdapter<String> deviceList;
	AudioTrack ir;
	int minBufSize;
	boolean playLock;
	String gdevice;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_iremoter_main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.irtitle);
		
		
		View.OnClickListener handler = new OnClickListener(){ 
	   		 
			 @Override 
			 public void onClick(View v) {
					// TODO Auto-generated method stub
				 	 String cmd="";
					 switch (v.getId()) {  
			            case R.id.vol_plus:  
			                cmd="VOL+";
			                break;
			            case R.id.vol_decrease:  
			                cmd="VOL-";
			                break;
			            case R.id.vol_mute:  
			            	cmd="MUTE";
			                break;
			            case R.id.ch_plus:  
			            	cmd="P+";
			                break;
			            case R.id.ch_decrease:  
			            	cmd="P-";
			                break;
			            case R.id.number1:
			            	cmd="1";
			                break;
			            case R.id.number2:  
			            	cmd="2";
			                break;
			            case R.id.number3:
			            	cmd="3";
			                break;
			            case R.id.number4:  
			            	cmd="4";
			                break;
			            case R.id.number5:
			            	cmd="5";
			                break;
			            case R.id.number6:  
			            	cmd="6";
			                break;
			            case R.id.number7: 
			            	cmd="7";
			                break;
			            case R.id.number8:  
			            	cmd="8";
			                break;
			            case R.id.number9:  
			            	cmd="9";
			                break;
			            case R.id.number0:
			            	cmd="0";
			            	break;
			            case R.id.power:
			            	cmd="POWER";
			            	break;
			            default:
			            	cmd="";
			            	break;
					 }
					sendSignal(gdevice,cmd);
				}
	   		};
		
        ImageButton ir_volup   = (ImageButton) findViewById(R.id.vol_plus);
        ir_volup.setOnClickListener(handler);
        ImageButton ir_voldown = (ImageButton) findViewById(R.id.vol_decrease);
        ir_voldown.setOnClickListener(handler);
        ImageButton ir_volmute = (ImageButton) findViewById(R.id.vol_mute);
        ir_volmute.setOnClickListener(handler);
        ImageButton ir_chup  = (ImageButton) findViewById(R.id.ch_plus);
        ir_chup.setOnClickListener(handler);
        ImageButton ir_chdown  = (ImageButton) findViewById(R.id.ch_decrease);
        ir_chdown.setOnClickListener(handler);
        ImageButton ir_number1  = (ImageButton) findViewById(R.id.number1);
        ir_number1.setOnClickListener(handler);
        ImageButton ir_number2  = (ImageButton) findViewById(R.id.number2);
        ir_number2.setOnClickListener(handler);
        ImageButton ir_number3  = (ImageButton) findViewById(R.id.number3);
        ir_number3.setOnClickListener(handler);
        ImageButton ir_number4  = (ImageButton) findViewById(R.id.number4);
        ir_number4.setOnClickListener(handler);
        ImageButton ir_number5  = (ImageButton) findViewById(R.id.number5);
        ir_number5.setOnClickListener(handler);
        ImageButton ir_number6  = (ImageButton) findViewById(R.id.number6);
        ir_number6.setOnClickListener(handler);
        ImageButton ir_number7  = (ImageButton) findViewById(R.id.number7);
        ir_number7.setOnClickListener(handler);
        ImageButton ir_number8  = (ImageButton) findViewById(R.id.number8);
        ir_number8.setOnClickListener(handler);
        ImageButton ir_number9  = (ImageButton) findViewById(R.id.number9);
        ir_number9.setOnClickListener(handler);
        ImageButton ir_number0  = (ImageButton) findViewById(R.id.number0);
        ir_number0.setOnClickListener(handler);
        ImageButton ir_power  = (ImageButton) findViewById(R.id.power);
        ir_power.setOnClickListener(handler);
        
        final Spinner spinDevice = (Spinner) findViewById(R.id.Spinner01);
		
        
		lirc = new Lirc();
	    playLock = false;
		// Initialize adapter for device spinner
	    deviceList = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
		deviceList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinDevice.setPrompt("Select a device");
    	spinDevice.setAdapter(deviceList);
		
    	
    	parse(LIRCD_CONF_FILE);

		spinDevice.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
		
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int pos,
					long id) {
			
				// TODO Auto-generated method stub
		    	gdevice=spinDevice.getSelectedItem().toString();
			}
		
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		    		
		    }); 
		
	    minBufSize = AudioTrack.getMinBufferSize(48000,
	    		AudioFormat.CHANNEL_CONFIGURATION_STEREO,
	    		AudioFormat.ENCODING_PCM_8BIT);
	    
	    ir = new AudioTrack(AudioManager.STREAM_MUSIC, 48000, 
				AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_8BIT, 
				minBufSize, AudioTrack.MODE_STREAM);
	    
	    ir.play();
	}
	
	

	public boolean parse (String config_file) {
	    	
	    	java.io.File file = new java.io.File(config_file);
	    	
	    	if (!file.exists()) {
	    		if (config_file != LIRCD_CONF_FILE)
	    			Toast.makeText(getApplicationContext(), "The Selected file doesn't exist", Toast.LENGTH_SHORT).show();
	    		else
	    			Toast.makeText(getApplicationContext(), "Configuartion file missing, please update the db", Toast.LENGTH_SHORT).show();
	    		return false;
	    	}
	    	
	    	if (lirc.parse(config_file) == 0) {
	 			Toast.makeText(getApplicationContext(), "Couldn't parse the selected file", Toast.LENGTH_SHORT).show();
	    		return false;
	    	}
	   
	    	// Save the file since it has been parsed successfully
	    	if (config_file != LIRCD_CONF_FILE) {
		        try {
		            FileInputStream in = new FileInputStream(config_file);
		            FileOutputStream out = new FileOutputStream(LIRCD_CONF_FILE);
		            byte[] buf = new byte[1024];
		            int i = 0;
		            while ((i = in.read(buf)) != -1) {
		                out.write(buf, 0, i);
		            }
		            in.close();
		            out.close();
		        } catch(Exception e) {
	    		
		        }
	    	}
	    	
	    	updateDeviceList();
	    	return true;
	    }
    
    public void updateDeviceList(){
        String [] str = lirc.getDeviceList();
        
        if (str == null){
 			Toast.makeText(getApplicationContext(), "Invalid, empty or missing config file", Toast.LENGTH_SHORT).show();
    		return;
        }
        deviceList.clear();
        for (int i=0; i<str.length; i++){
        	deviceList.add(str[i]);
        }
    }
    
    void sendSignal(String device, String cmd) {
    	
	    byte buffer[] = lirc.getIrBuffer(device, cmd, minBufSize+1024);
		
	    if (buffer == null) {
	    	return;
	    }

	    ir.setStereoVolume(1, 1);
	    int res = ir.write(buffer, 0, buffer.length);

	    Log.e("BUFFER", "written/buf_size/min_buf_size: "+res+"/"+buffer.length+"/"+minBufSize);
	}
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.iremoter_main, menu);
		return true;
	}

}
